package com.hongshu.common.core.utils.ip;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hongshu.common.core.constant.Constants;
import com.hongshu.common.core.utils.HttpUtils;
import com.hongshu.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取地址类
 *
 * @author hongshu
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "未知";

    public static String getRealAddressByIP(String ip) {
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网";
        }
        try {
            String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSON.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            String addr = obj.getString("addr");

            // 拼接详细地址，优先显示 region/city，如果都没有就用 addr
            StringBuilder sb = new StringBuilder();
            if (region != null) sb.append(region);
            if (city != null) {
                if (sb.length() > 0) sb.append(" ");
                sb.append(city);
            }
            if (sb.length() == 0 && addr != null) {
                sb.append(addr);
            }
            return sb.length() > 0 ? sb.toString() : UNKNOWN;
        } catch (Exception e) {
            log.error("获取地理位置异常 {}: {}", ip, e.getMessage());
        }
        return UNKNOWN;
    }
}
